package com.edu.chapter09_kotlin

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.edu.chapter09_kotlin.model.GameInfo
import com.edu.chapter09_kotlin.model.ItemBean
import com.edu.chapter09_kotlin.network.OkHttpHelper
import java.util.Random

class RecyclerViewActivity : AppCompatActivity(), View.OnClickListener {
    private var isLoadingMore = false
//    private var list: MutableList<GameInfo> = mutableListOf()
    val myAdapter = MyAdapter()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycler_view)
        findViewById<TextView>(R.id.btn_swap).setOnClickListener(this)
        val recyclerView = findViewById<RecyclerView>(R.id.rv_list)
        recyclerView.layoutManager = LinearLayoutManager(this)

        loadData()
        recyclerView.adapter = myAdapter
    }

    override fun onClick(v: View?) {
        if (v != null) {
            if (v.id == R.id.btn_swap) {
                val intent = Intent(this, MyPageActivity().javaClass)
                startActivity(intent)
            }
        }
    }

    private fun loadData() {
        //adapter.
        isLoadingMore = true
        val num: Int = Random().nextInt(800 - 200 + 1) + 200
        OkHttpHelper().searchGames(num) { result ->
            runOnUiThread {
                result.onSuccess { response ->
                    // 添加新数据并更新UI
                    response.data?.let { data ->
                        myAdapter.add(data) // 假设adapter有一个add方法，并且响应数据中的records是列表
                    }
                }
                result.onFailure { error ->
                    // 处理错误
                    Log.e("loadData", "Error: ${error.message}")
                }
                // 无论成功失败，都要更新加载状态
                isLoadingMore = false
            }
        }
        isLoadingMore = false
    }
}